package com.motu.monstercity.server.game.logichandler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.hazelcast.internal.server.Server;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBChatMsg;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.Common.PBUserFeastRecord;
import com.motu.monstercity.protocol.Common.PBUserFeastRecord.Builder;
import com.motu.monstercity.protocol.CsGameFeast.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.feast.FeastConstant;
import com.motu.monstercity.server.game.commondata.feast.FeastJoin;
import com.motu.monstercity.server.game.commondata.feast.FeastMain;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.maintask.HonorReward;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.system.UserExp;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.timedtask.TimeTaskCmd;
import com.motu.monstercity.server.game.timedtask.TimedTaskManager;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.Lock;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class FeastHandler {
	// CMD_GAME_FEAST_MAIN_INFO = 71201;// 下发用户派对信息表
	public static Object CMD_GAME_FEAST_MAIN_INFO(RequestParam clientParam) throws Exception {
		CSGameFeastMainInfoRequest request = CSGameFeastMainInfoRequest.parseFrom(clientParam.getData());
		CSGameFeastMainInfoResponse.Builder response = CSGameFeastMainInfoResponse.newBuilder();
		long userId = clientParam.getUserId();

		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserFeastInfo userFeastInfo = FeastManager.getUserFeastInfo(userId);
		pbUserData.getFeastBuilder().setUserFeastInfo(userFeastInfo.takeInitBuilder());

		UserInfo userInfo = GameUser.getUserInfo(userId);
		for (FeastMain feastMain : FeastManager.getFeastMainMap().values()) {
			ServerFeast serverFeast = FeastManager.getServerFeast(userInfo.getServerId(), userId, feastMain.getId());
			if (serverFeast != null) {
				response.putMyFeast(serverFeast.getId(), serverFeast.takeInitBuilder().build());
			}
		}

		List<UserFeastRecord> list = FeastManager.getUserFeastRecordList(userId);
		List<UserFeastRecord> listNew = list.stream().sorted(Comparator.comparingLong(UserFeastRecord::getAddTime).reversed()).collect(Collectors.toList());
		boolean isAdd1 = false;// 101
		boolean isAdd2 = false;// 102
		boolean isAdd3 = false;// 201
		for (UserFeastRecord userFeastRecord : listNew) {
			if (userFeastRecord.getIsShow() == 1) {
				continue;
			}
			if (userFeastRecord.getFeastMainId() == FeastConstant.FEAST_101) {
				if (!isAdd1) {
					response.putShow(userFeastRecord.getFeastId(), userFeastRecord.takeInitBuilder().build());
					isAdd1 = true;
				}
			}
			if (userFeastRecord.getFeastMainId() == FeastConstant.FEAST_102) {
				if (!isAdd2) {
					response.putShow(userFeastRecord.getFeastId(), userFeastRecord.takeInitBuilder().build());
					isAdd2 = true;
				}
			}
			if (userFeastRecord.getFeastMainId() == FeastConstant.FEAST_201) {
				if (!isAdd3) {
					response.putShow(userFeastRecord.getFeastId(), userFeastRecord.takeInitBuilder().build());
					isAdd3 = true;
				}
			}
		}


		return response;
	}

	// CMD_GAME_FEAST_LIST = 71202;// 获取派对列表
	public static Object CMD_GAME_FEAST_LIST(RequestParam clientParam) throws Exception {
		CSGameFeastListRequest request = CSGameFeastListRequest.parseFrom(clientParam.getData());
		CSGameFeastListResponse.Builder response = CSGameFeastListResponse.newBuilder();
		long userId = clientParam.getUserId();
		long dbid = request.getDbid();

		UserInfo userInfo = GameUser.getUserInfo(userId);
		List<ServerFeast> list = FeastManager.getServerFeastList(userInfo.getServerId());
		for (ServerFeast serverFeast : list) {
			if (serverFeast.getId() > dbid) {
				response.putServerFeastList(serverFeast.getId(), serverFeast.takeInitBuilder().build());
			}
		}

		PBUserData.Builder pbUserData = response.getUserBuilder();
		List<UserFeastPopup> popupList = FeastManager.getUserFeastPopupList(userId);
		for (UserFeastPopup userFeastPopup : popupList) {
			ProtoDataUtils.updatePBUserData(pbUserData, userFeastPopup, true);
		}

		return response;
	}

	// CMD_GAME_FEAST_ENTER = 71203;// 查看派对的座位列表.进入某个派对  公共数据. [2]每次打开请求，进入自己的派对，会根据规则生成机器人
	public static Object CMD_GAME_FEAST_ENTER(RequestParam clientParam) throws Exception {
		CSGameFeastEnterRequest request = CSGameFeastEnterRequest.parseFrom(clientParam.getData());
		CSGameFeastEnterResponse.Builder response = CSGameFeastEnterResponse.newBuilder();
		long userId = clientParam.getUserId();

		long createrId = request.getCreaterId();
		int feastMainId = request.getFeastMainId();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		ServerFeast serverFeast = FeastManager.getServerFeast(userInfo.getServerId(), createrId, feastMainId);
		FeastMain feastMain = FeastManager.getFeastMain(feastMainId);
		if (serverFeast == null) {
			return ErrorWord.NOT_DATA;
		}

		if (serverFeast.isCommonFeast() && userId == serverFeast.getUserId()) {// // 进入自己的普通派对，会根据规则生成机器人
			int robotNum = AllParam.FEAST_JOIN_ROBOT_MAX_NUM - serverFeast.getGuestNum();
			if (robotNum > 0) {
				boolean isUpdate = false;
				FeastJoin robotJoin = FeastManager.getRobotJoin();
				for (int i=0; i<robotNum; i++) {
					long robotAddTime = serverFeast.getJoinTime() + TimeUtils.HOUR;// 机器人的加入时间
					if (robotAddTime < TimeUtils.getCurTime()) {// 时间超过每1小时，生成一个机器
						isUpdate = true;
						FeastManager.handleJoinFeast(serverFeast, userInfo, robotJoin, robotAddTime, true);// 生成参与数据
					}
				}
				if (serverFeast.getGuestNum() >= feastMain.getGuestNum()) {// // 普通派对人满自动结束  派对完成处理的业务逻辑
					FeastManager.handleFeastComplete(serverFeast, serverFeast.getAddTime());
					response.setIsComplete(true);// 派对已结束
					isUpdate = false;
				}
				if (isUpdate) {
					serverFeast.update();
				}
			}
		}

		List<ServerFeastSeat> list = FeastManager.getServerFeastSeatList(serverFeast.getId());
		for (ServerFeastSeat serverFeastSeat : list) {
			response.putSeatList(serverFeastSeat.getId(), serverFeastSeat.takeInitBuilder().build());
		}
		response.setServerFeast(serverFeast.takeInitBuilder());

		return response;
	}

	// CMD_GAME_FEAST_CHAT_RECORD = 71204; // 获取派对聊天记录
	public static Object CMD_GAME_FEAST_CHAT_RECORD(RequestParam clientParam) throws Exception {
		CSGameFeastChatRecordRequest request = CSGameFeastChatRecordRequest.parseFrom(clientParam.getData());
		CSGameFeastChatRecordResponse.Builder response = CSGameFeastChatRecordResponse.newBuilder();
		long userId = clientParam.getUserId();

		long feastId = request.getFeastId();
		long dbid = request.getDbid();
		List<FeastChatRecord> list = FeastManager.getFeastChatRecordList(feastId);
		for (FeastChatRecord feastChatRecord : list) {
			if (feastChatRecord.getId() > dbid) {
				response.putChatList(feastChatRecord.getId(), feastChatRecord.takeBuilder().build());
			}
		}

		return response;
	}

	// CMD_GAME_FEAST_GET_CREATE_RECORD = 71205;// 获取我的举办派对记录
	public static Object CMD_GAME_FEAST_GET_CREATE_RECORD(RequestParam clientParam) throws Exception {
		CSGameFeastGetCreateRecordRequest request = CSGameFeastGetCreateRecordRequest.parseFrom(clientParam.getData());
		CSGameFeastGetCreateRecordResponse.Builder response = CSGameFeastGetCreateRecordResponse.newBuilder();
		long userId = clientParam.getUserId();
		long dbid = request.getDbid();

		PBUserData.Builder pbUserData = response.getUserBuilder();
		List<UserFeastRecord> list = FeastManager.getUserFeastRecordList(userId);
		for (UserFeastRecord userFeastRecord : list) {
			if (userFeastRecord.getId() > dbid) {
				pbUserData.getFeastBuilder().putCreateList(userFeastRecord.getId(), userFeastRecord.takeInitBuilder().build());
			}
		}

		return response;
	}

	// CCMD_GAME_FEAST_GET_JOIN_RECORD = 71206;// 获取某个普通派对的参与记录 [2]每次打开请求
	public static Object CMD_GAME_FEAST_GET_JOIN_RECORD(RequestParam clientParam) throws Exception {
		CSGameFeastGetJoinRecordRequest request = CSGameFeastGetJoinRecordRequest.parseFrom(clientParam.getData());
		CSGameFeastGetJoinRecordResponse.Builder response = CSGameFeastGetJoinRecordResponse.newBuilder();
		long userId = clientParam.getUserId();
		long feastId = request.getFeastId();

		List<UserFeastJoinDetail> list = FeastManager.getUserFeastJoinDetailList(feastId);
		for (UserFeastJoinDetail userFeastJoinDetail : list) {
			response.putJoinList(userFeastJoinDetail.getId(), userFeastJoinDetail.takeInitBuilder().build());
		}

		return response;
	}

	// CMD_GAME_FEAST_CREATE = 71208;//举办派对
	public static Object CMD_GAME_FEAST_CREATE(RequestParam clientParam) throws Exception {
		CSGameFeastCreateRequest request = CSGameFeastCreateRequest.parseFrom(clientParam.getData());
		CSGameFeastCreateResponse.Builder response = CSGameFeastCreateResponse.newBuilder();
		long userId = clientParam.getUserId();

		int feastMainId = request.getFeastMainId();// 派对类型id
		boolean isThree = request.getIsThree();//
		List<Integer> allowJoinType = request.getAllowListList();// (普通派对允许的参加赞助类型)1，2，3
		JsonArray jsoinTypeAllow = new JsonArray();
		for (Integer allowType : allowJoinType) {
			jsoinTypeAllow.add(allowType);
		}

		FeastMain feastMain = FeastManager.getFeastMain(feastMainId);// 私人派对的配置
		if (feastMain == null) {
			return ErrorWord.NOT_DATA;
		}
		if (feastMain.isCommonFeast() && allowJoinType.size() == 0) {
			return ErrorWord.BAD_PARAM;// 设置不对
		}
		UserInfo userInfo = GameUser.getUserInfo(userId);
		int severId = userInfo.getServerId();
		ServerFeast serverFeast = FeastManager.getServerFeast(severId, userId, feastMainId);
		if (serverFeast != null) {
			return ErrorWord.REPEATED_OPERATION;
		}

		List<RewardItem> costItem = CommonUtils.takeReawrdItemFromStr(feastMain.getCostItem());// 需要消耗的道具
		if (isThree) {
			CommonUtils.multipleItemList(costItem, AllParam.FEAST_THREE_REWARD);// 消耗3倍的道具
		}
		if (!BagManager.checkNeedItemNum(userInfo, costItem)) {
			return ErrorWord.ITEM_LACK;// 道具不足
		}

		// 执行逻辑
		// 创建定时任务
		long createTime = TimeUtils.getCurTime();
		JsonObject jsonObject = new JsonObject();
		jsonObject.put("uniq_key", FeastManager.getFeastUniqKey(userId, feastMainId));
		jsonObject.put("server_id", userInfo.getServerId());
		jsonObject.put("end_time", createTime + feastMain.getDurationTime());
		TimedTaskManager.sendMainTaskRetry(TimeTaskCmd.MAIN_SERVER_FEAST, jsonObject);// 发送失败,需要进行重发

		PBUserData.Builder pbUserData = response.getUserBuilder();
		RewardManager.subReward(userInfo, costItem, pbUserData, LogType.FEAST_CREATE);

		serverFeast = new ServerFeast(severId, userInfo, feastMainId, isThree, jsoinTypeAllow, createTime);
		if (!serverFeast.isCommonFeast()) {// 盛典派对0人给个保底积分
			serverFeast.putScore(serverFeast.countCelebScore());
		}
		serverFeast.doCreate();
		response.setFeast(serverFeast.takeInitBuilder());
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_193, 1);// 更新主线任务,成就,日常任务的进度
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_55, 1);// 参与{0}次派对
		RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_55, 1);
		if (!serverFeast.isCommonFeast()) {// 盛典派对 放在docreate后面，不然没有dbid值
			FeastManager.publicFeastAllUser(userInfo, serverFeast);// 给本服所有玩家进行广播, 通知有盛典派对举办
		}

		return response;
	}

	// CMD_GAME_FEAST_JOIN = 71209;// 参加别人的派对
	public static Object CMD_GAME_FEAST_JOIN(RequestParam clientParam) throws Exception {
		CSGameFeastJoinRequest request = CSGameFeastJoinRequest.parseFrom(clientParam.getData());
		CSGameFeastJoinResponse.Builder response = CSGameFeastJoinResponse.newBuilder();
		long userId = clientParam.getUserId();

		long createrId = request.getCreaterId();// 举办者的userid
		int feastMainId = request.getFeastMainId();// 派对类型 id
		int joinType = request.getJoinType();

		UserInfo userInfo = GameUser.getUserInfo(userId);
		FeastMain feastMain = FeastManager.getFeastMain(feastMainId);
		List<RewardItem> costReward = null;
		if (feastMain == null) {
			return ErrorWord.NOT_DATA;
		}
		FeastJoin feastJoin = null;
		ServerFeast serverFeast = null;
		UserFeastInfo userFeastInfo = FeastManager.getUserFeastInfo(userId);
		if (feastMain.isCommonFeast()) {
			feastJoin = FeastManager.getFeastJoin(feastMain.getType(), joinType);
			if (feastMain == null || feastJoin == null) {
				return ErrorWord.NOT_DATA;
			}
			costReward = CommonUtils.takeReawrdItemFromStr(feastJoin.getCostItem());// 消耗道具
			if (!BagManager.checkNeedItemNum(userInfo, costReward)) {
				return ErrorWord.ITEM_LACK;// 道具不足
			}
			if (joinType == FeastConstant.FEAST_JOIN_TYPE_GOLD && userFeastInfo.getJoinNum() >= AllParam.FEAST_JOIN_GOLD_MAX_NUM) {// 金币赞助有次数限制
				return ErrorWord.ALREADY_MAX;// 次数达到上限
			}
		}

		Lock lock = null;
		String lockKey = "";
		try {
			lockKey = LockKey.getServerFeastlock(createrId, feastMainId);
			lock = MainService.getVertLock(lockKey);
			serverFeast = FeastManager.getServerFeast(userInfo.getServerId(), createrId, feastMainId);
			if (serverFeast == null || serverFeast.getServerId() != userInfo.getServerId() || serverFeast.getUserId() == userId) {
				return ErrorWord.WRONG_STATUS;// 派对不存在或已经结束,或是不是本服,自己举办的派对不能参加
			}
			if (feastMain.getGuestNum() > 0 && serverFeast.getGuestNum() >= feastMain.getGuestNum()) {
				return ErrorWord.ALREADY_MAX;// 有限制人数时 人数满了
			}
			long feastId = serverFeast.getId();
			ServerFeastSeat serverFeastSeat = FeastManager.getServerFeastSeat(feastId, userId);
			if (serverFeastSeat != null) {
				return ErrorWord.REPEATED_OPERATION;// 这个派对已经参加了
			}
			if (feastMain.isCommonFeast()) {
				JsonArray allowJsonArray = serverFeast.getJoinTypeAllowArray();
				if (!Tool.isInList(allowJsonArray, joinType)) {
					return ErrorWord.ENTITY_NOT_EXIST;// 该赞助类型被限制了
				}
			}

			// 参加派对， 增加派对的参与人数，生成派对座位信息serverFeastSeat，生成派对的参与详情user_feast_join_detail
			FeastManager.handleJoinFeast(serverFeast, userInfo, feastJoin, TimeUtils.getCurTime(), false);
			// 把座位数据,并下发给客户端
			serverFeastSeat = FeastManager.getServerFeastSeat(serverFeast.getId(), userId);
			if (serverFeastSeat != null) {
				response.setSeat(serverFeastSeat.takeInitBuilder());
			}
			serverFeast.update();
			response.setFeast(serverFeast.takeBuilder());
		} catch (InvalidProtocolBufferException e) {
			return ErrorWord.PROTOCOL_PARSE_FAILED;
		} finally {// 释放锁
			MainService.releaseVertLock(lock);
		}

		PBUserData.Builder pbUserData = response.getUserBuilder();

		if (feastMain.isCommonFeast()) {// 普通派对参加需要扣除道具
			RewardManager.subReward(userInfo, costReward, pbUserData, LogType.FEAST_JOIN);// 扣除道具
			if (joinType == FeastConstant.FEAST_JOIN_TYPE_GOLD) {
				userFeastInfo.addJoinNum(1);
				userFeastInfo.update();
				pbUserData.getFeastBuilder().getUserFeastInfoBuilder().setJoinNum(userFeastInfo.getJoinNum());// 特殊处理，获得积分会更新userFeastInfo。score字段
			}
			if (serverFeast.getGuestNum() >= feastMain.getGuestNum()) {// // 普通派对人满自动结束  派对完成处理的业务逻辑
				FeastManager.handleFeastComplete(serverFeast, serverFeast.getAddTime());
				response.setIsComplete(true);// 派对已结束
			}
		}

		List<RewardItem> rewardItemList = FeastManager.countFeastJoinReward(userInfo, serverFeast, feastJoin);// 参加派对获得的奖励 有技能会对人气进行加成
		RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.FEAST_JOIN);// 参加庆典派对获得奖励
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_194, 1);// 更新主线任务,成就,日常任务的进度
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_55, 1);// 参与{0}次派对
		RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_55, 1);

		return response;
	}

	// CMD_GAME_FEAST_CHAT = 71210; // 发送派对聊天
	public static Object CMD_GAME_FEAST_CHAT(RequestParam clientParam) throws Exception {
		CSGameFeastChatRequest request = CSGameFeastChatRequest.parseFrom(clientParam.getData());
		CSGameFeastChatResponse.Builder response = CSGameFeastChatResponse.newBuilder();
		long userId = clientParam.getUserId();

		long createrId = request.getCreaterId();// 举办者的userid
		int feastMainId = request.getFeastMainId();// 派对类型 id
		String msg = request.getContent();
		if (Tool.isEmpty(msg)) {
			return ErrorWord.WORD_LENGTH_WRONG;
		}
		UserInfo userInfo = GameUser.getUserInfo(userId);
		int serverId = userInfo.getServerId();
		ServerFeast serverFeast = FeastManager.getServerFeast(serverId, createrId, feastMainId);
		if (serverFeast == null) {
			return ErrorWord.ENTITY_NOT_EXIST;//当前没有这个派对或者已经结束
		}
		if (userId != createrId) {// 不是举办者,要判断是否有参加这个派对
			ServerFeastSeat mySeat = FeastManager.getServerFeastSeat(serverFeast.getId(), userId);
			if (mySeat == null) {
				return ErrorWord.WRONG_STATUS;// 未参加派对
			}
		}
		UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
		if (!ChatManager.isCanChat(userInfo, userExtInfo)) {
			return ErrorWord.WRONG_STATUS;// 被禁言或是太频繁发言
		}
		// 超过最大长度自动截断
		if (msg.length() > AllParam.CHAT_CONTENT_MAX) {
			msg = msg.substring(0, AllParam.CHAT_CONTENT_MAX);
		}
		// 过滤敏感字符
		try {
			msg = SensitivewordEngine.replaceWordBySdk(msg, userExtInfo.getPlatform());
		} catch (Exception e) {
			return ErrorWord.BAD_WORD;
		}

		// 屏蔽# $符号
		msg = Tool.replaceColorChar(msg);

		// 执行逻辑
		FeastChatRecord feastChatRecord = new FeastChatRecord(serverFeast.getId(), userInfo, msg);
		feastChatRecord.doCreate();
		response.setChat(feastChatRecord.takeBuilder());// 下发给客户端

		// 广播给派对的所有玩家
		BoardcastManager.publicFeastMessage(userInfo, serverFeast, feastChatRecord.takeBuilder(), feastChatRecord.getId());

		userExtInfo.putChatTime(TimeUtils.getCurTime());
		userExtInfo.update();// 更新最后一次发言时间

		return response;
	}

	// CMD_GAME_FEAST_SEARCH = 71211;// 根据举办者的userid 搜索派对
	public static Object CMD_GAME_FEAST_SEARCH(RequestParam clientParam) throws Exception {
		CSGameFeastSearchRequest request = CSGameFeastSearchRequest.parseFrom(clientParam.getData());
		CSGameFeastSearchResponse.Builder response = CSGameFeastSearchResponse.newBuilder();
		long userId = clientParam.getUserId();

		long uid = request.getUid();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		for (FeastMain feastMain : FeastManager.getFeastMainMap().values()) {
			ServerFeast serverFeast = FeastManager.getServerFeast(userInfo.getServerId(), uid, feastMain.getId());
			if (serverFeast != null) {
				response.setFeast(serverFeast.takeInitBuilder().build());
			}
		}

		return response;
	}

	// CMD_GAME_FEAST_SET_ALLOW = 71212;// 设置派对的赞助类型
	public static Object CMD_GAME_FEAST_SET_ALLOW(RequestParam clientParam) throws Exception {
		CSGameFeastSetAllowRequest request = CSGameFeastSetAllowRequest.parseFrom(clientParam.getData());
		CSGameFeastSetAllowResponse.Builder response = CSGameFeastSetAllowResponse.newBuilder();
		long userId = clientParam.getUserId();

		int feastMainId = request.getFeastMainId();// 派对类型id
		List<Integer> allowJoinType = request.getAllowListList();// (普通派对允许的参加赞助类型)1，2，3
		JsonArray jsoinTypeAllow = new JsonArray();
		for (Integer allowType : allowJoinType) {
			jsoinTypeAllow.add(allowType);
		}

		FeastMain feastMain = FeastManager.getFeastMain(feastMainId);// 私人派对的配置
		if (feastMain == null) {
			return ErrorWord.NOT_DATA;
		}
		if (!feastMain.isCommonFeast() || allowJoinType.size() == 0) {
			return ErrorWord.BAD_PARAM;// 设置不对
		}
		UserInfo userInfo = GameUser.getUserInfo(userId);
		int severId = userInfo.getServerId();
		ServerFeast serverFeast = FeastManager.getServerFeast(severId, userId, feastMainId);
		if (serverFeast == null) {
			return ErrorWord.ENTITY_NOT_EXIST;// 派对已经结束了
		}

		// 执行逻辑
		serverFeast.putJoinTypeAllow(allowJoinType.toString());
		serverFeast.update();
		response.setFeast(serverFeast.takeInitBuilder());

		return response;
	}


	// CMD_GAME_FEAST_ADD_POPUP = 71213;// 标记为已经弹窗过
	public static Object CMD_GAME_FEAST_ADD_POPUP(RequestParam clientParam) throws Exception {
		CSGameFeastAddPopupRequest request = CSGameFeastAddPopupRequest.parseFrom(clientParam.getData());
		CSGameFeastAddPopupResponse.Builder response = CSGameFeastAddPopupResponse.newBuilder();
		long userId = clientParam.getUserId();

		long dbid = request.getFeastDbid();
		UserFeastPopup userFeastPopup = FeastManager.getUserFeastPopup(userId, dbid);
		if (userFeastPopup != null) {
			return ErrorWord.REPEATED_OPERATION;// 已经记录过了
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		userFeastPopup = new UserFeastPopup();
		userFeastPopup.putUserId(userId);
		userFeastPopup.putFeastDbid(dbid);
		userFeastPopup.putPopupTime(TimeUtils.getCurTime());
		userFeastPopup.doCreate();
		ProtoDataUtils.updatePBUserData(pbUserData, userFeastPopup, true);

		return response;
	}


	// CMD_GAME_FEAST_LIST_USERID = 71215;// 根据userid 查看对方举办的所有派对信息
	public static Object CMD_GAME_FEAST_LIST_USERID(RequestParam clientParam) throws Exception {
		CSGameFeastListUseridRequest request = CSGameFeastListUseridRequest.parseFrom(clientParam.getData());
		CSGameFeastListUseridResponse.Builder response = CSGameFeastListUseridResponse.newBuilder();
		long userId = clientParam.getUserId();
		long targetUserId = request.getTargetUserId();// 对方的userid

		UserInfo userInfoTarget = GameUser.getUserInfo(targetUserId);
		if (userInfoTarget != null) {
			for (FeastMain feastMain : FeastManager.getFeastMainMap().values()) {
				ServerFeast serverFeast = FeastManager.getServerFeast(userInfoTarget.getServerId(), targetUserId, feastMain.getId());
				if (serverFeast != null) {
					response.putServerFeastList(serverFeast.getId(), serverFeast.takeInitBuilder().build());
				}
			}
		}

		return response;
	}

	// CMD_GAME_FEAST_SHARE = 71216;// 分享到世界聊天频道，邀请参加派对
	public static Object CMD_GAME_FEAST_SHARE(RequestParam clientParam) throws Exception {
		CSGameFeastShareRequest request = CSGameFeastShareRequest.parseFrom(clientParam.getData());
		CSGameFeastShareResponse.Builder response = CSGameFeastShareResponse.newBuilder();
		long userId = clientParam.getUserId();

		long createrId = request.getCreaterId();// 举办者的userid
		int feastMainId = request.getFeastMainId();// 派对类型 id

		UserInfo userInfo = GameUser.getUserInfo(userId);
		int serverId = userInfo.getServerId();
		ServerFeast serverFeast = FeastManager.getServerFeast(serverId, createrId, feastMainId);
		if (serverFeast == null) {
			return ErrorWord.ENTITY_NOT_EXIST;//当前没有这个派对或者已经结束
		}

		UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
		if (!ChatManager.isCanChat(userInfo, userExtInfo)) {
			return ErrorWord.WRONG_STATUS;// 被禁言或是太频繁发言
		}

		int msgId = 0;
		if (serverFeast.getFeastMainId() == FeastConstant.FEAST_101) {
			msgId = MailConstant.FEAST_SHARE_MSG_117;
		} else if (serverFeast.getFeastMainId() == FeastConstant.FEAST_102) {
			msgId = MailConstant.FEAST_SHARE_MSG_118;
		} else if (serverFeast.getFeastMainId() == FeastConstant.FEAST_201) {
			msgId = MailConstant.FEAST_SHARE_MSG_119;
		}

		// 执行逻辑
		String content = ChatManager.getSystemMsg(msgId);

		JsonObject jsonObject = new JsonObject();
		JsonArray link = new JsonArray();
		JsonObject tmp = new JsonObject();
		tmp.put("linkType", 30001);
		JsonArray jsonArray2 = new JsonArray().add(createrId).add(feastMainId);
		tmp.put("values", jsonArray2.toString());

		link.add(tmp);
		jsonObject.put("link", link);

		int chatType = ChatManager.CHAT_TYPE_SERVER;// 世界聊天频道
		int subType = ChatManager.CHAT_SUB_TYPE_COMMON;// 普通聊天
		int groupId = ChatManager.getGroupId(serverId, chatType);
		ChatPublic cp = new ChatPublic(userInfo, groupId, serverId, content, chatType, subType, jsonObject.toString());
		cp.doCreate();

		// 广播给玩家
		PBChatMsg.Builder chatMsgBuilder = cp.takeBuilder();
		BoardcastManager.publicChatMessage(userInfo, chatMsgBuilder);
		response.setChatMsg(chatMsgBuilder);

		return response;
	}


	// CMD_GAME_FEAST_UPDATE_SHOW = 71217;// 更新派对记录是否已经展示过
	public static Object CMD_GAME_FEAST_UPDATE_SHOW(RequestParam clientParam) throws Exception {
		CSGameFeastUpdateShowRequest request = CSGameFeastUpdateShowRequest.parseFrom(clientParam.getData());
		CSGameFeastUpdateShowResponse.Builder response = CSGameFeastUpdateShowResponse.newBuilder();
		long userId = clientParam.getUserId();

		int feastMainId = request.getFeastMainId();

		List<UserFeastRecord> list = FeastManager.getUserFeastRecordList(userId);
		for (UserFeastRecord userFeastRecord : list) {
			if (userFeastRecord.getFeastMainId() == feastMainId && userFeastRecord.getIsShow() == 0) {
				userFeastRecord.putIsShow(1);// 更新状态
				userFeastRecord.update();
			}
		}

		return response;
	}
}
